package collect

import (
	"context"
	"github.com/1141520944/go-library/library/log"
	"github.com/fsnotify/fsnotify"
	"time"
)

func NewFileListen(ctx context.Context, log *log.Logger) (*fileListen, error) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return nil, err
	}
	f := &fileListen{
		watcher: watcher,
		paths:   make([]string, 0, 10),
		Opt:     make(chan fOpt, 10),
		Info:    make(chan fInfo, 10),
		ctx:     ctx,
		log:     log,
	}
	// 添加监控
	go f.initListener()
	//添加修改器
	go f.initModifier()
	return f, err
}

// initModifier 修改器
func (f *fileListen) initModifier() {
	for {
		select {
		case val := <-f.Opt:
			switch val.sign {
			case Add:
				f.paths = append(f.paths, val.data)
				f.log.Infow("listen add", val.data)
				if err := f.watcher.Add(val.data); err != nil {
					f.Info <- fInfo{
						err:  err,
						path: val.data,
						time: time.Now().Format(time.DateTime),
						Sign: Add,
					}
				}
			case Delete:
			case Update:
			}
		case <-f.ctx.Done():
			println("modifier clean")
			break
		}
	}
}

// initListener 监听器
func (f *fileListen) initListener() {
	for {
		select {
		case event, ok := <-f.watcher.Events:
			if !ok {
				return
			}
			f.Info <- fInfo{
				event: event,
				err:   nil,
				path:  "",
				time:  time.Now().Format(time.DateTime),
				Sign:  0,
			}
		case err, ok := <-f.watcher.Errors:
			if !ok {
				return
			}
			f.Info <- fInfo{
				err:  err,
				path: "",
				time: time.Now().Format(time.DateTime),
				Sign: 0,
			}
		case <-f.ctx.Done():
			println("listener clean")
			break
		}
	}
}
